package com.foreknow.test;

import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 反射机制
 * 1. Class.forName("完整路径")
 * 2. 对象.getClass()
 * 3. 任何类型.class
 */
public class ReflectionDemo {
    public void getNameTest() {
        String name = "fender";
        //获取到每一个字节码文件对应的Class类型的对象.
        Class cls = name.getClass();
        System.out.println("String name: "+cls.getName());
        Button button = new Button();
        Class clazzButton = button.getClass();
        System.out.println("Button name: "+clazzButton.getName());
        Class superClass = clazzButton.getSuperclass();
        System.out.println("Button Supper class: "+superClass.getName());
    }

    public String testMethod(String str, HashMap hashMap) {
        String returnStr = "xxxxx";
        System.out.println("map data:"+hashMap.get("key"));
        return returnStr;
    }

    public void getTestMethod() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //1. 获取到类对象
        Class cls = Class.forName("com.foreknow.test.ReflectionDemo");
        //2. 获取方法
        Class[] ptypes = new Class[2];
        ptypes[0] = Class.forName("java.lang.String");
        ptypes[1] = Class.forName("java.util.HashMap");
        Method method = cls.getMethod("testMethod",ptypes); //第一个参数为方法名，第二个参数为形参
        //3. 调用方法 method.invoke(调用方法所属的对象,实参);
        Object[] args = new Object[2];
        args[0] = "hello";
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("key","123");
        args[1] = map;
        String result = (String) method.invoke(new ReflectionDemo(),args);
        System.out.println(result);
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        ReflectionDemo reflectionDemo = new ReflectionDemo();
        reflectionDemo.getTestMethod();
//        HashMap<String,Object> map = new HashMap<String,Object>();
//        map.put("key","123");
//        String rs = reflectionDemo.testMethod("fender",map);
//        System.out.println(rs);
    }
}
